"""扫描问题Repository"""
from typing import Optional, List, Dict, Any
from sqlalchemy.orm import Session
from sqlalchemy import and_, or_
from app.models.issue import Issue
from app.models.scan_issue_extension import ScanIssueExtension
from app.repositories.base import BaseRepository


class IssueRepository(BaseRepository[Issue]):
    """扫描问题数据访问层"""

    def __init__(self, db: Session):
        super().__init__(Issue, db)

    def get_by_record_id(
        self,
        record_id: int,
        skip: int = 0,
        limit: int = 100,
        filters: Optional[Dict[str, Any]] = None,
        order_by: Optional[str] = None,
    ) -> List[Issue]:
        """根据扫描记录ID获取问题列表"""
        query = self.db.query(Issue).filter(Issue.record_id == record_id)

        # 应用额外过滤条件
        if filters:
            for field, value in filters.items():
                if hasattr(Issue, field):
                    query = query.filter(getattr(Issue, field) == value)

        # 应用排序
        if order_by:
            parts = order_by.split()
            field_name = parts[0]
            if len(parts) > 1 and parts[1].lower() == "desc":
                query = query.order_by(getattr(Issue, field_name).desc())
            else:
                query = query.order_by(getattr(Issue, field_name))
        else:
            query = query.order_by(Issue.level.desc(), Issue.line_number)

        return query.offset(skip).limit(limit).all()

    def get_by_confirm_status(
        self, record_id: int, confirm_status: str
    ) -> List[Issue]:
        """根据确认状态获取问题列表"""
        return self.get_by_record_id(
            record_id=record_id,
            filters={"confirm_status": confirm_status},
        )

    def get_extensions(self, issue_id: int) -> Dict[str, Any]:
        """获取问题的扩展字段数据"""
        extensions = (
            self.db.query(ScanIssueExtension)
            .filter(ScanIssueExtension.issue_id == issue_id)
            .all()
        )
        return {ext.field_name: ext.field_value for ext in extensions}

    def count_by_record_id(self, record_id: int) -> int:
        """统计扫描记录的问题数"""
        return self.db.query(Issue).filter(Issue.record_id == record_id).count()

    def count_by_level(self, record_id: int, level: str) -> int:
        """统计指定级别的问题数"""
        return (
            self.db.query(Issue)
            .filter(and_(Issue.record_id == record_id, Issue.level == level))
            .count()
        )

